package p.ithorns.framework.schedule;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * ScheduledService
 *
 * @author ithorns
 * @version 1.0
 * @date 2021/12/25 21:28
 */
@Configuration
public class ScheduledService implements SchedulingConfigurer {

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    private final List<TaskMeta> taskMetas = new ArrayList<>();
    private final Map<String, ScheduledFuture> futures = new HashMap<>();

    @PostConstruct
    public void init() {
        taskMetas.add(new TaskMeta("a", 10));

        for (TaskMeta meta : taskMetas) {
            String id = meta.getId();
            long delay = meta.getDelay();
            ScheduledFuture<?> future = taskScheduler.scheduleWithFixedDelay(new FixDelayTask(), delay);
            futures.put(id, future);
        }

    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler);
    }


    public void refresh(TaskMeta task) {
        String id = task.getId();

        ScheduledFuture future = futures.get(id);
        if (future == null) {
            return;
        }

        future.cancel(false);
        future = taskScheduler.scheduleWithFixedDelay(new FixDelayTask(), task.getDelay());
        futures.put(id, future);
    }

    class FixDelayTask implements Runnable {
        @Override
        public void run() {
            System.out.println("AAAAAAA");
        }
    }

    public static class TaskMeta {
        private String id;
        private long delay;

        public TaskMeta(String id, long delay) {
            this.id = id;
            this.delay = delay;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public long getDelay() {
            return delay;
        }

        public void setDelay(long delay) {
            this.delay = delay;
        }
    }


}
